import sys
import importlib

sys.path.append(sys.path[0] + '/../../')

# POI增删改查
class POICurd:

    def __init__(self):
        DataBase = importlib.import_module('util.DataBase').DataBase
        POIEntity = importlib.import_module('src.poi.POIEntity').POIEntity
        Urllib3Request = importlib.import_module(
            'util.Urllib3Request').Urllib3Request

        self.urlConfig = importlib.import_module('config.urlConfig')

        self.dataBase = DataBase({
            'schema': 'bmapdata',
            'tableName': 'poi_bmap'
        })

        self.urllib3Request = Urllib3Request()

        self.POIEntity = POIEntity

    def requestPoiData(self, param):
        results = []
        urllib3Request = self.urllib3Request
        urlConfig = self.urlConfig
        data = urllib3Request.urllib3Get(urlConfig.urlDict['POISearch'], param)
        for result in data["results"]:
            poiEntity = self.POIEntity(result)
            results.append(poiEntity)
        data["results"] = results
        return data

    def insertPoiData(self, datas):
        db = self.dataBase
        insertValues = []
        for data in datas:
            res = db.query(
                "select uid from {0}.{1} where uid=%s".format(self.dataBase.schema, self.dataBase.tableName),
                [data.uid])
            # 已有值做更新操作，否则插入
            if data.uid is None:
                continue
            if res is not None:
                db.delete("delete from {0}.{1} where uid='{2}'".format(self.dataBase.schema, self.dataBase.tableName, data.uid), None)

            geopoint = db.query(
                'select public.st_setsrid(public.st_makepoint({0}, {1}),4326)'.format(data.lng, data.lat), None)
            insertValues.append((data.uid, data.name, data.address,
                                 data.province, data.city, data.area,
                                 data.street_id, data.tag, data.type, data.detail_url, data.telephone, round(data.lng, 4),
                                 round(data.lat, 4), geopoint))

        db.insert(
            "insert into "
            "{0}.{1}(uid,name,address,province,city,area,street_id,tag,type,detail_url,telephone,lng,lat,geom) "
            "values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)".format(self.dataBase.schema, self.dataBase.tableName),
            insertValues)
